<?php
namespace Home\Controller;

use Model\LiveSettingModel;
use Model\PaperModel;
use Model\PaperResultsModel;
use Model\QuestionModel;
use Model\RoomModel;
use Model\TeacherModel;
use Model\UserModel;
use Model\WxUsersModel;
use Think\Controller;

class QuestionController extends BaseController
{

    public function __construct()
    {
        parent::__construct();

    }

    public function index()
    {
        $userId = cookie("id");
        if($userId == ""){
            $this->error("请登录后答题","/");
        }
        $roomId = intval(I("get.Rid"));

        if(empty($roomId)){
            $this->error("非法参数","/");
        }
        $data['roomId'] = $roomId;
        $roomsModel = new RoomModel();
        $rooms = $roomsModel->find($roomId);
        if($rooms['isOpenPaper'] == 0){
            $this->error("此直播课程未开放答题！","/Online/play/id/{$roomId}");
        }
        $teacher = $this->getTeacherMeaage($rooms['liveUrlId']);

        $liveSettingModel = new LiveSettingModel();
        $liveSetting = $liveSettingModel->where($data)->find();
        if(empty($liveSetting)){
            $this->error("目前暂无试卷！","");
        }
        $paperId = $liveSetting['paperId'];
        $paperModel = new PaperModel();
        $paper = $paperModel->find($paperId);
        $question = array_filter(explode(",",$paper['titles']));
        if(empty($question)){
            $this->error("此试卷暂无题目","/");
        }

        //查询是否已经答题过了
        $paperResultModel = new PaperResultsModel();
        $findResult = $paperResultModel->where("`paperId` = {$paperId} AND `userId` = {$userId}")->find();
        if(!empty($findResult)){
            $this->error("您已经答过此试卷了,马上看结果","/Question/Result/Rid/{$roomId}");
        }

        $questionModel = new QuestionModel();
        $where['id'] = array("in",$question);
        $questionList = $questionModel->where($where)->select();

        $this->assign("rooms",$rooms);
        $this->assign("teacher",$teacher);
        $this->assign("paper",$paper);
        $this->assign("questionList",$questionList);

        $this->display();

    }

    /**
     * 提交试卷
     */
    public function postPaper(){
        $userId = cookie("id");
        $paper = I("post.paper");
        $paperId = $paper['paperId'];
        $roomId = $paper['roomId'];
        $answer = $paper['questionId'];
        $time = $paper['time'];
        $paperResultModel = new PaperResultsModel();
        $findResult = $paperResultModel->where("`paperId` = {$paperId} AND `userId` = {$userId}")->find();
        if(!empty($findResult)){
            $this->ajaxReturn(['status'=>"has"]);
        }
        $paperModel = new PaperModel();
        $paperInfo = $paperModel->find($paperId);

        //直播间
        $data['roomId'] = $roomId;
        //试卷名称
        $data['paperId'] = $paperInfo['id'];
        $data['paperName'] = $paperInfo['name'];
        $data['time'] = $time;
        $questions = array_filter(explode(",",$paperInfo['titles']));
        $questionModel = new QuestionModel();
        $where['id'] = array("in",$questions);
        $questionList = $questionModel->where($where)->select();
        foreach($questionList as $k=>$v){
            $arrangeQuestionList[$v['id']] = $v;
        }
        //试卷的提纲
        $data['question'] = json_encode($arrangeQuestionList);
        $data['answer'] = json_encode($answer);
        $data['userId'] = $userId;
        $data['createTime'] = date("Y-m-d H:i:s");
        $paperResultModel = new PaperResultsModel();
        $savePaperResult = $paperResultModel->add($data);
        if($savePaperResult){
            $status['status'] = 'ok';
        }else{
            $status['status'] = 'error';
        }
        //发送得分消息
        /**
         * 1:此用户是否关注了微信号findByUninid
         */
        $userModel = new UserModel();
        $userMessage = $userModel->find($userId);
        $unionId = $userMessage['unionId'];
        if(!empty($unionId)){
            $userWxModel = new WxUsersModel();
            $userWxMessage = $userWxModel->where("`unionid` = '{$unionId}'")->find();
            if( !empty($userWxMessage)){
                $studentName = $userMessage['studentName'];
                $openid = $userWxMessage['openid'];
                $roomModel = new RoomModel();
                $roomMessage = $roomModel->find($roomId);
                $roomName = $roomMessage['name'];
                $examResult =  $this->getScores($arrangeQuestionList,$answer);
                $analysis = "暂无分析内容";
                $remark = "点击“详情”立即前往查看答题详情和专业的分析报告。";
                $return = $this->sendAllUsersTemplateMessage($studentName,$roomName,$examResult,$analysis,$remark,$openid);
                $status['code'] = $return;
            }
        }


        $this->ajaxReturn($status);

    }
    public function result(){

        $userId = cookie("id");
        $roomId = intval(I("get.Rid"));
        if(empty($userId)){
            $this->error("请先登录","/");
        }
        if(empty($roomId)){
            $this->error("非法参数","/");
        }
        $data['roomId'] = $roomId;
        $roomsModel = new RoomModel();
        $rooms = $roomsModel->find($roomId);
        $teacher = $this->getTeacherMeaage($rooms['liveUrlId']);

        $liveSettingModel = new LiveSettingModel();
        $liveSetting = $liveSettingModel->where($data)->find();
        $paperId = $liveSetting['paperId'];
        $paperModel = new PaperModel();
        $paper = $paperModel->find($paperId);

        $question = array_filter(explode(",",$paper['titles']));

        $questionModel = new QuestionModel();
        $where['id'] = array("in",$question);
        $questionList = $questionModel->where($where)->select();

        //查询答题情况
        $paperResultsModel = new PaperResultsModel();
        $paperResult = $paperResultsModel->where("`roomId` = {$roomId} AND `paperId` = {$paperId} AND `userId` = {$userId}")->find();
        $paperResult['question'] = json_decode($paperResult['question'],true);
        $paperResult['answer'] = json_decode($paperResult['answer'],true);
        $scores = $this->getScores($paperResult['question'],$paperResult['answer']);
        $errorAnswer = $this->getErrorAnswer($paperResult['question'],$paperResult['answer']);
        $this->assign("paperResult",$paperResult);
        $this->assign("errorAnswer",$errorAnswer);
        $this->assign("scores",$scores);
        $this->assign("rooms",$rooms);
        $this->assign("teacher",$teacher);
        $this->assign("paper",$paper);
        $this->assign("questionList",$questionList);

        $this->display();
    }

    public function paper(){
        $roomId = I("post.roomId");
        $data['roomId'] = $roomId;
        $roomsModel = new RoomModel();
        $rooms = $roomsModel->find($roomId);
        $liveSettingModel = new LiveSettingModel();
        $liveSetting = $liveSettingModel->where($data)->find();
        $paperId = $liveSetting['paperId'];
        $paperModel = new PaperModel();
        $paper = $paperModel->find($paperId);
        $question = array_filter(explode(",",$paper['titles']));
        $questions['roomId'] = $rooms['id'];
        $questions['paperId'] = $paper['id'];
        foreach($question as $v){

            $questions['questionId'][$v] ="";
        }
        $this->ajaxReturn($questions);
    }



    /**
     * @param $liveUrlId
     * @return array
     */
    public function getTeacherMeaage($liveUrlId){
        $teacherModel = new  TeacherModel();
        $liveSetting = new LiveSettingModel();
        $settingMessage = $liveSetting->where(" `liveUrlId` = {$liveUrlId} ")->find();

        $teacher = $teacherModel->find($settingMessage['teacherId']);

        switch ($teacher['level'])
        {
            case 1:
                $teacher['levelTitle'] = "特级教师";
                break;
            case 2:
                $teacher['levelTitle'] = "普通教师";
                break;

        }


        return $teacher;
    }

    /**
     * @about 计算用户考试成绩
     *
     * @param array $question question
     * @param array $answer answer
     */
    public function getScores($question,$answer){

        $scores = 0;

        foreach($question as $k=>$v){
            if($v['answer'] == $answer[$k]){
                $scores += $v['score'];
            }
        }

        return $scores;

    }

    /**
     * @about 获取用户错题以及答案
     *
     * @param array $question question
     * @param array $answer answer
     */
    public function getErrorAnswer($question,$answer){
        foreach($question as $k=>$v){
            if($v['answer'] != $answer[$k]){
                $errorQuestion[] = ['question'=>$k,'errorNumber'=>$answer[$k]];
            }
        }
        return $errorQuestion;
    }

    /**
     * @param $courseName
     * @param $date
     * @param $remark
     * @param $nickName
     * @param $openid
     * @return mixed
     */
    public function sendAllUsersTemplateMessage($first,$roomName,$examResult,$analysis,$remark,$openid){
        $wxId = C("WX_ID");
        $wxSecret = C("WX_SECRET");
        $token_access_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $wxId . "&secret=" . $wxSecret;
        $res = file_get_contents($token_access_url); //获取文件内容或获取网络请求的内容
        $result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP 变量
        $access_token = $result['access_token'];

        $customMessageSendUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token."";
        $postDataArr['touser'] = "".$openid."";
        $postDataArr['template_id'] ="i9mJsXQuKuvf-vq8dK0s8xmv0aMxlUmFFtBBPd8xm_4";
        $postDataArr['url'] ="http://www.baidu.com";
        $postDataArr['data'] =  array(
            'first'=>array("value"=>"尊敬的".$first."家长，您好：".$first."于".date("Y年m月d日")."参加了".$roomName."的测评：","color"=>"#1fe3b3"),
            'examResult'=>array("value"=>"".$examResult."","color"=>"#1fe3b3"),
            'analysis'=>array("value"=>"".$analysis."","color"=>"#1fe3b3"),
            'remark'=>array("value"=>"".$remark."","color"=>"#e33b5a"),
        );
        $postJosnData = json_encode($postDataArr);
        $ch = curl_init($customMessageSendUrl);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postJosnData);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $data = curl_exec($ch);
        $data = json_decode($data,true);
        return $data['errcode'];

    }

}